<?php
require_once(dirname(dirname(dirname(__FILE__))) . '/app.php');

need_login();

// 具体同步设置
$web = strval($_GET['web']);
$action = strval($_GET['action']);

if ( 'local_sync' == $action ) {
	// 本地认证设定
	if($_POST['email'] && $_POST['password']){
		$ret = LSync::Connect($login_user_id, $web, $_POST['email'], $_POST['password']);
		if($ret){
			Session::Set('notice', '同步设置成功！');
			redirect(null);
		}
	}
	Session::Set('error', '同步设置时输入的账号或密码有误！');
	redirect(null);
}
elseif( 'make_auth_url' == $action ){
	// 合成远程验证的url	
	$callbackUrl = ROOT_URL;
	$callbackUrl .= '/account/ajax/sync_settings.php?web='.$web.'&action=remote_auth';
	$ret = LSync::MakeAuthUrl($web, $callbackUrl);
	Session::Set('authUrl', $ret['aurl']);
	Session::Set('keys', $ret['keys']);
}
elseif ( 'remote_auth' == $action ) {
	// 远程认证设定
	$keys = Session::Get('keys', true);
	$ret = LSync::Connect($login_user_id, $web, $keys['oauth_token'], $keys['oauth_token_secret']);
	if($ret){
		Session::Set('notice', '同步设置成功！');
		redirect(WEB_ROOT.'/account/sync.php');
	} else{
		Session::Set('error', '同步设置失败！');
		redirect(WEB_ROOT.'/account/sync.php');
	}
}
elseif ( 'cancel' == $action ) {
	// 取消同步设定
	LSync::Disconnect($login_user_id, $web);
	Session::Set('notice', '取消同步设置成功！');
	$sync = Table::Fetch('sync', $login_user_id);
	json(null, 'refresh');
}

$html = render('account_ajax_sync_settings');
json($html, 'dialog');